package com.xyd.wechat.service.impl;

import com.xyd.wechat.common.ApplicationConfig;
import com.xyd.wechat.service.AccessTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


@Service
public class AccessTokenServiceImpl implements AccessTokenService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private RestTemplate restTemplate;

    private String accessToken = null;

    /**
     * access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效。
     */
    @Scheduled(fixedRate = 7200000)
    private void initGetToken() {
        String url = String.format(applicationConfig.getWechatAccessTokenUrl(), applicationConfig.getWechatAppId(), applicationConfig.getWechatAppSecret());
        ResponseEntity<Map> entity = restTemplate.getForEntity(url, Map.class);
        Map rsMap = entity.getBody();
        if (rsMap.get("access_token") != null) {
            accessToken = (String) rsMap.get("access_token");
            logger.info("获取access_token，{}", accessToken);
        } else {
            logger.error("获取access_token，错误时微信会返回错误码等信息。{}", rsMap);
        }
    }

    @Override
    public String getAccessToken() {
        if (accessToken == null) {
            initGetToken();
        }
        return accessToken;
    }
}
